#-*-coding:utf-8-*
import requests
import json
from pandas import Series, DataFrame
from sqlalchemy import create_engine


def getToken():
    url = "http://localhost:8010/api"

    payload = "Username=admin&Password=40123"
    headers = {
        'Content-Type': "application/x-www-form-urlencoded",
        'Cache-Control': "no-cache",
       
        }

    jsonResponse = requests.request("POST", url, data=payload, headers=headers)
    hjson = json.loads(jsonResponse.text)

    return hjson['result']


def getVideoData(token):
    url = "http://localhost:8010/api/services"
    payload = "Username=admin"
    headers = {
        'Content-Type': "application/x-www-form-urlencoded",
        'Authorization': "Bearer "+token,
        'Cache-Control': "no-cache",
       
    }

    response = requests.request("POST", url, data=payload, headers=headers)

    return(response.text)
def writeToSQL(video_data):
    video_json = json.loads(video_data)
    result = video_json['result']
    items = result['items']

    d = DataFrame(items)
    yconnect = create_engine('mysql+pymysql://root:@localhost:3306/cam?charset=utf8')
    d.to_sql('camera', yconnect, schema='cam', if_exists='replace', index=False)

if __name__ == '__main__':
    token = getToken()
    # print token
    video_data = getVideoData(token)
    # print video_data
    what = writeToSQL(video_data)
